import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'
import type { RootState } from '../../app/store'

/* 
计数器功能模块的redux模块
向外暴露:
  reducer
  同步和异步action creator
  读取state数据的select函数
*/

// state的类型
interface CounterState {
  count: number
}

// 初始state
const initialState: CounterState = {
  count: 1,
}

// 创建返回异步action的action creator函数
  // 参数一: 标识名称, 用于组成action对象的type名称
  // 参数二: 包含异步操作的函数, 必须返回promise对象, promise的结果值会传递给action对象的payload
        // Promise<T>: T指定为成功的value类型
export const incrementAsync = createAsyncThunk(
  'counter/incrementAsync',
  (num: number) => {
    return new Promise<number>((resolve) => {
      setTimeout(() => {
        resolve(num)
      }, 1000)
    })
  }
)

// 创建当前redux模块的管理对象slice
export const counterSlice = createSlice({
  name: 'counter', // 标识名称 => 用于组成action对象的type名称
  initialState, // 初始状态
  reducers: { // 所有同步action对应的reducer
    increment: (state, action: PayloadAction<number>) => { // 内部会自动生成对应的action creator
      state.count += action.payload
    },
    decrement: (state, action: PayloadAction<number>) => { // 内部会自动生成对应的action creator
      state.count -= action.payload
    },
  },
  extraReducers: (builder) => { // 异步action对应的reducer
    // incrementAsync 异步成功对应的reducer
    builder.addCase(incrementAsync.fulfilled, (state, action) => {
      state.count += action.payload
    })
  },
})

// 暴露内部自动生成的action creator函数 (根据上面的reducers配置)
export const { increment, decrement } = counterSlice.actions

// 暴露用于读取state数据的select函数 => 简化组件编码
export const selectCount = (state: RootState) => state.counter.count

// 暴露内部自动生成的reducer函数
export default counterSlice.reducer